package com.ifighter.service.user;

import java.sql.SQLException;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class UserService {

	private SQLiteDatabase db; 

	public UserService(SQLiteDatabase db){
		this.db = db;
	}

	public long createNewUser(String sName, String sLastname, String sNickanme, String sPassword, String sEmail){

		ContentValues contentValues = new ContentValues();

		contentValues.put("NAME", sName);
		contentValues.put("LASTNAME", sLastname);
		contentValues.put("NICKNAME", sNickanme);
		contentValues.put("PASSWORD", sPassword);
		contentValues.put("EMAIL", sEmail);

		return db.insert(User.TABLE, null, contentValues);
	}

	/**
	 * 
	 * @param nickname
	 * @param password
	 * @return User
	 * @throws SQLException
	 */
	public User getUserByCredential(String nickname, String password) throws SQLException{

		StringBuffer sql       = new StringBuffer();
		String[] selectionArgs = {nickname, password};
		Cursor cursor          = null;
		User result            = null;

		sql.append("SELECT * FROM ");
		sql.append(User.TABLE);
		sql.append(" WHERE NICKNAME = ? AND PASSWORD = ?");

		cursor = this.db.rawQuery(sql.toString(), selectionArgs);

		if(cursor.moveToNext())
			result = new User(cursor);

		return result;
	}

	/**
	 * 
	 * @param nickname
	 * @return boolean
	 */
	public boolean checkUsername(String nickname){

		StringBuffer sql       = new StringBuffer();
		String[] selectionArgs = {nickname};
		Cursor cursor          = null;
		boolean result         = true;

		sql.append("SELECT * FROM ");
		sql.append(User.TABLE);
		sql.append(" WHERE NICKNAME = ?");

		cursor = this.db.rawQuery(sql.toString(), selectionArgs);

		if(cursor.moveToNext())
			result = false;

		return result;
	}
}